import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_kit_plus/flutter_kit.dart';

import '../../commont/button.dart';
import '../../model/model.dart';
import '../../model/model_default.dart';
import '../../tool/assets.dart';

class DelayItem extends StatefulWidget {
  ChannelModel ch;
  void Function(ChannelModel) onClick;
  void Function(ChannelModel) onChange;
  DelayItem(
      {super.key,
      required this.ch,
      required this.onClick,
      required this.onChange});

  @override
  State<DelayItem> createState() => _DelayItemState();
}

class _DelayItemState extends State<DelayItem> {
  final _controller = TextEditingController();
  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    _controller.text = '';
    _controller.addListener(() {
      String text = _controller.text;
      print('=======<  输入的  delay  === ${_controller.text}');

      // 自动添加前导0
      if (text.isNotEmpty && text[0] == '.') {
        _controller.text = '0$text';
      } else if (text.length > 1 && text[0] == '0' && text[1] != '.') {
        _controller.text = text.substring(1, text.length);
      }

      ///输入文本转换成数值是 0，并且字符串不止1位，不转换成ch的值
      // if (_controller.text.float == 0) {
      //   return;
      // }
    });
  }

  @override
  Widget build(BuildContext context) {
    _controller.text = widget.ch.delay;
    return Column(
      children: [
        ///通道按钮
        Flexible(
            flex: 5,
            child: kTextButton(
              name: widget.ch.name,
              fontSize: 14,
              enable: widget.ch.enable,
              groundColor: bg_color(widget.ch),
              textColor: text_color(widget.ch, selectColor: Colors.black),
              borderColor: border_color(widget.ch),
              onClick: globalModel.enable == false
                  ? null
                  : (p0) {
                      setState(() {
                        widget.ch.enable = true;
                        widget.ch.select = !widget.ch.select;
                      });
                      widget.onClick(widget.ch);
                    },
            )),
        const SizedBox(height: 5),

        ///通道延迟
        Flexible(
          flex: 4,
          child: Container(
            decoration: BoxDecoration(
                color: Color_bg_view,
                borderRadius: BorderRadius.circular(5),
                border: Border.all(color: border_color(widget.ch), width: 0.5)),
            child: Row(
              children: [
                Flexible(
                  flex: 5,
                  child: SizedBox(
                    child: TextField(
                      enabled: widget.ch.enable,
                      textAlignVertical: TextAlignVertical.center,
                      textAlign: TextAlign.center,
                      cursorHeight: 10, // 设置光标高度
                      cursorWidth: 0.5,
                      cursorColor: Colors.black, //设置光标颜色
                      style: TextStyle(
                          fontSize: 10,
                          color:
                              text_color(widget.ch, selectColor: Colors.black)),
                      controller: _controller,
                      keyboardType:
                          const TextInputType.numberWithOptions(decimal: true),

                      ///输入规则限制
                      inputFormatters: [
                        LengthLimitingTextInputFormatter(5), // 限制输入最大长度为3
                        //FilteringTextInputFormatter.digitsOnly, // 只允许输入数字
                        FilteringTextInputFormatter(
                          RegExp(r'^\d*\.?\d*$'), // 允许数字和一个小数点
                          allow: true,
                        ),
                      ],

                      ///响应方法
                      onTap: globalModel.enable == false
                          ? null
                          : () {
                              setState(() {
                                widget.ch.select = true;
                              });
                              widget.onClick(widget.ch);
                            },
                      onChanged: globalModel.enable == false
                          ? null
                          : (value) {
                              double v = value.float;
                              if (widget.ch.delay_type == 'ms' &&
                                  v > widget.ch.max_delay) {
                                widget.ch.delay = '8';
                              } else if (widget.ch.delay_type == 'cm' &&
                                  v > widget.ch.max_delay * 34.3) {
                                widget.ch.delay = '274';
                              } else if (widget.ch.delay_type == 'in' &&
                                  v > widget.ch.max_delay * 34.3 * 0.3937) {
                                widget.ch.delay = '108';
                              } else {
                                widget.ch.delay = value;
                              }
                              widget.onChange(widget.ch);
                              widget.onClick(widget.ch);
                            },
                      onSubmitted: (value) => widget.onChange(widget.ch),
                      onEditingComplete: () => widget.onChange(widget.ch),

                      ///边框设置
                      decoration: const InputDecoration(
                        isDense: true, // 密集模式，减少内部空间
                        contentPadding: EdgeInsets.only(top: 1), // 取消内边距
                        border: InputBorder.none, // 设置无边框
                        enabledBorder: InputBorder.none, // 输入框启用时无边框
                        focusedBorder: InputBorder.none, // 输入框获得焦点时无边框
                        // constraints: const BoxConstraints(
                        //   maxWidth: 40,
                        //   maxHeight: 20,
                        // ),
                      ),
                    ),
                  ),
                ),
                Center(
                    child:
                        Container(color: border_color(widget.ch), width: 0.5)),
                Flexible(
                  flex: 4,
                  child: InkWell(
                    onTap: globalModel.enable == false
                        ? null
                        : () {
                            setState(() {
                              handle_delay(widget.ch);
                            });
                            widget.onClick(widget.ch);
                          },
                    child: Center(
                      child: Text(
                        widget.ch.delay_type,
                        textAlign: TextAlign.center,
                        style: TextStyle(
                            fontSize: 10,
                            color: text_color(widget.ch,
                                selectColor: Colors.black)),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }
}

void handle_delay(ChannelModel ch) {
  double v = ch.delay.float;
  if (ch.delay_type == 'ms') {
    ch.delay_type = 'cm';
    v = (v * 34.3).roundDouble(0);
    v = max(ch.min_delay, v);
    v = min((ch.max_delay * 34.3).roundDouble(0), v);
  } else if (ch.delay_type == 'cm') {
    v = (v * 0.3937).roundDouble(0);
    ch.delay_type = 'in';
    v = max(ch.min_delay, v);
    v = min((ch.max_delay * 34.3 * 0.3937).roundDouble(0), v);
  } else if (ch.delay_type == 'in') {
    ch.delay_type = 'ms';
    v = v / 34.3 / 0.3937;
    v = max(ch.min_delay, v);
    v = min(ch.max_delay, v);
  }
  ch.delay = v.roundDouble(1).toString();
}
